<template>
    <div>
        <el-dialog title="个人信息" v-bind:visible="showAble" v-bind:before-close="closeUpdateUserInformation" width="40%">
            <div style="text-align: left">
                <el-divider>个人信息</el-divider>
                <el-form label-position="right" label-width="100px" style="margin: 30px;" v-model="userInformaion">
                    <!-- <el-input ></el-input> -->
                    <el-form-item label="工号">
                        <el-input v-model="userInformaion.userName" style="width: 100%"></el-input>
                    </el-form-item>
                    <el-form-item label="昵称">
                        <el-input v-model="userInformaion.userRealName" style="width: 100%"></el-input>
                    </el-form-item>
                    <el-form-item label="身份">
                        <el-select v-model="userInformaion.userType" style="width: 100%">
                            <el-option label="部门主管" value="department_manager" :disabled="userDepartmentIdDisabled"></el-option>
                            <el-option label="员工" value="employee" ></el-option>
                            <el-option label="经理" value="manager" :disabled="userDepartmentIdDisabled"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="年龄">
                        <el-input v-model="userInformaion.userAge" style="width: 100%"></el-input>
                    </el-form-item>
                    <el-form-item label="电话号码">
                        <el-input v-model="userInformaion.userPhoneNumber" style="width: 100%"></el-input>
                    </el-form-item>
                    <el-form-item label="部门">
                        <el-select v-model="userInformaion.userDepartmentId" style="width: 100%" :disabled="userDepartmentIdDisabled">
                            <el-option v-for="department in departments" :key="department.department_id" :value="department.department_id"
                                :label="department.department_name"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="密码">
                        <el-input type="password" v-model="userInformaion.password"></el-input>
                    </el-form-item>
                    <el-form-item label="重复密码">
                        <el-input type="password" v-model="userInformaion.passwordRepeat"></el-input>
                    </el-form-item>
                    <div style="text-align: center">
                        <el-button type="primary" style="width: 200px;" @click="addOrChangeEmployee">{{
                            addOrChange==="add"? "新增用户": "更新信息" }}
                        </el-button>
                        <el-button @click="closeUpdateUserInformation" style="width: 200px;">取消更新</el-button>
                    </div>
                </el-form>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import axios from "axios";
    import qs from "qs"

    export default {
        name: "updateUserInformation",
        data: function() {
            return {
                userInformaion: {
                    userId: "",
                    userName: "",
                    userRealName: "",
                    userType: "",
                    userAge: "",
                    userPhoneNumber: "",
                    userDepartmentId: "",
                    userDepartmentName: "",
                    password: "",
                    passwordRepeat: ""
                },
                departments: [{
                    department_id: "",
                    department_name: ""
                }],
                userDepartmentIdDisabled: false
            }
        },
        props: {
            showAble: {
                type: Boolean,
                required: true
            },
            changeUserId: {
                type: Number,
                default: null
                // required: true
            },
            addOrChange: {
                type: String,
                required: "true"
            }
        },
        methods: {
            /**
             * @description 检查表单是否符合条件
             */
            checkUserInformaion: function() {
                // check 工号
                if (this.userInformaion.userName.length === 0) {
                    this.$message({
                        message: "请检查是否输入工号",
                        type: "warning"
                    })
                    return false;
                }

                // check 昵称
                if (this.userInformaion.userRealName.length === 0) {
                    this.$message({
                        message: "请检查是否输入昵称",
                        type: "warning"
                    })
                    return false;
                }

                // check 年龄
                try {
                    console.log(this.userInformaion.userAge);
                    let t = Number(this.userInformaion.userAge)
                    if (t <= 18 || t >= 100) {
                        this.$message({
                            message: "请检查年龄是否在范围内",
                            type: "warning"
                        })
                        return false;
                    }
                } catch (e) {
                    this.$message({
                        message: "请检查年龄是否输入正确",
                        type: "warning"
                    })
                    return false;
                }

                // check phone number
                if (this.userInformaion.userPhoneNumber.length !== 11) {
                    this.$message({
                        message: "请检查手机号码的位数是否输入正确",
                        type: "warning"
                    })
                    return false;
                } else {
                    for (var i = 0; i <= 10; ++i) {
                        if (!(this.userInformaion.userPhoneNumber[i] >= '0' &&
                                this.userInformaion.userPhoneNumber[i] <= '9')) {
                            this.$message({
                                message: "请检查手机号码的位数是否输入正确",
                                type: "warning"
                            })
                            return false;
                        }
                    }
                }

                // check department
                if (this.userInformaion.userDepartmentId.length === 0) {
                    this.$message({
                        message: "请选择部门",
                        type: "warning"
                    })
                    return false;
                }

                // check password
                if (this.userInformaion.password === this.userInformaion.passwordRepeat) {
                    if (this.userInformaion.password.length <= 8) {
                        this.$message({
                            message: "密码长度太短，请重新设置（大于8位数）",
                            type: "warning"
                        })
                        return false;
                    }
                } else {
                    this.$message({
                        message: "两次密码不一致",
                        type: "warning"
                    })
                }

                return true;
            },

            /**
             * @description 关闭当前窗口
             * @function closeUpdateUserInformation
             */
            closeUpdateUserInformation: function() {
                this.$emit("closeUpdateUserInformation");
                console.log("get closeUpdateUserInformation")
            },

            /**
             * @description 提交当前更改后的信息，如果服务器端不存在，那么将新建一个用户
             * @function addOrChangeEmployee
             */
            addOrChangeEmployee: function() {
                console.log("this is addOrChangeEmployee");

                if (this.checkUserInformaion() === false) {
                    return;
                }

                var _this = this;
                axios.post("http://127.0.0.1:8000/api/user/", JSON.stringify({
                        action: _this.addOrChange,
                        user_type: _this.userInformaion.userType,
                        user_id: _this.userInformaion.userId,
                        user_name: _this.userInformaion.userName,
                        user_real_name: _this.userInformaion.userRealName,
                        user_age: _this.userInformaion.userAge,
                        user_department_id: _this.userInformaion.userDepartmentId,
                        user_phone_number: _this.userInformaion.userPhoneNumber,
                        user_password: _this.userInformaion.password
                    }))
                    .then(function(response) {
                        console.log("addOrChangeEmployee success");
                        console.log(response)
                        if (response.data.status == 0) {
                            _this.$message({
                                message: '恭喜你，操作成功！',
                                type: 'success'
                            });
                        } else {
                            _this.$message({
                                message: '抱歉，操作失败！',
                                type: 'error'
                            });
                        }
                        _this.closeUpdateUserInformation();
                    })
                    .catch(function(error) {
                        console.log(error);
                        _this.$message({
                            message: '抱歉，操作失败！',
                            type: 'error'
                        });
                    })
            },

            /**
             * @description 获取部门信息
             * @function getDepartments
             */
            getDepartments: function() {
                var _this = this;
                axios.get("http://127.0.0.1:8000/api/department/")
                    .then(function(response) {
                        console.log("get department")
                        console.log(response.data.data)

                        for (var i = 0; i < response.data.data.length; i++) {
                            if (_this.userInformaion.userDepartmentId === response.data.data[i].department_id) {
                                _this.userInformaion.userDepartmentName = response.data.data[i]
                                    .department_name;
                            }
                        }
                        _this.departments = response.data.data;
                        console.log("this is get departments")
                        console.log(_this);
                    })
                    .catch(function(error) {
                        console.log(error);
                    })
            },

            /**
             * @description 获取个人信息
             * @function getUserInformation
             */
            getUserInformation: function() {
                var _this = this;
                axios.get("http://127.0.0.1:8000/api/user/", {
                        params: {
                            "user_id": _this.changeUserId
                        }
                    })
                    .then(function(response) {
                        _this.userInformaion.userId = response.data.data.user_id;
                        _this.userInformaion.userName = response.data.data.user_name;
                        _this.userInformaion.userRealName = response.data.data.user_real_name;
                        _this.userInformaion.userType = response.data.data.user_type;
                        _this.userInformaion.userAge = response.data.data.user_age;
                        _this.userInformaion.userPhoneNumber = response.data.data.user_phone_number;
                        _this.userInformaion.userDepartmentId = response.data.data.user_department_id;
                        _this.userInformaion.password = response.data.data.password;
                        _this.userInformaion.passwordRepeat = response.data.data.password;
                    })
                    .catch(function(error) {
                        console.log(error);
                    })
            },

            /**
             * @description  检查是否需要禁止选择员工
             */
            checkUserDepartmentIdDisabled: function() {
                if (this.$store.state.userType === "department_manager") {
                    var _this = this;
                    axios.get("http://127.0.0.1:8000/api/user/", {
                            params: {
                                "user_id": _this.$store.state.userId
                            }
                        })
                        .then(function(response) {
                            console.log("ggggggggggggggggggggggg");
                            console.log(response);
                            _this.userInformaion.userDepartmentId = response.data.data.user_department_id;
                            console.log(_this.userInformaion);
                        })
                        .catch(function(error) {
                            console.log(error);
                        });
                    this.userDepartmentIdDisabled = true;
                }
            }
        },
        watch: {
            showAble: function() {
                if (this.addOrChange === "change") {
                    console.log("change User id is changed.")
                    this.userInformaion.userId = this.changeUserId;
                    var _this = this;
                    this.getDepartments();
                    this.getUserInformation();
                    this.checkUserDepartmentIdDisabled();
                } else {
                    console.log("add User id is changed.")
                    // this.userInformaion.userId = this.changeUserId;
                    var _this = this;
                    _this.userInformaion.userId = "";
                    _this.userInformaion.userName = "";
                    _this.userInformaion.userRealName = "";
                    _this.userInformaion.userType = "";
                    _this.userInformaion.userAge = "";
                    _this.userInformaion.userPhoneNumber = "";
                    _this.userInformaion.userDepartmentId = "";
                    _this.userInformaion.password = "";
                    _this.userInformaion.passwordRepeat = "";
                    this.checkUserDepartmentIdDisabled();
                }
            }
        },
        mounted: function() {
            this.getDepartments();
            this.checkUserDepartmentIdDisabled();
        }
    }
</script>

<style scoped>

</style>
